package com.ruoyi.system.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.stereotype.Component;

/**
 * @Auther:尤志杰
 * @Date:2025/2/26 14:08
 * @Description: GenerateCode
 * @Version 1.0.0
 */
@Component("generateCode")
public class GenerateCode {

    public String getGeneratedCode(String chinese) {

        StringBuilder mnemonicCode = new StringBuilder();

        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();

        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        for (char c : chinese.toCharArray() ) {
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")){
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null && pinyinArray.length > 0){
                        mnemonicCode.append(pinyinArray[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }else {
                mnemonicCode.append(c);
            }
        }

        return mnemonicCode.toString();
    }

}
